package org.desktop.web.client.project.window.handler;

import java.util.ArrayList;
import java.util.List;

import org.desktop.web.client.project.grid.ProjectGrid;
import org.desktop.web.client.project.grid.SubProjectsGrid;
import org.desktop.web.client.project.service.ProjectService;
import org.desktop.web.client.project.service.ProjectServiceAsync;
import org.desktop.web.client.timesheet.service.TimesheetService;
import org.desktop.web.client.timesheet.service.TimesheetServiceAsync;
import org.desktop.web.client.user.UserService;
import org.desktop.web.client.user.UserServiceAsync;
import org.desktop.web.shared.domain.entities.Project;
import org.desktop.web.shared.domain.entities.SubProject;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.widget.core.client.AutoProgressBar;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.box.ConfirmMessageBox;
import com.sencha.gxt.widget.core.client.event.DialogHideEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.DialogHideEvent.DialogHideHandler;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.grid.Grid;

public class RemoveSubprojectHandler implements SelectHandler {
	/**
	 * Classe interna che gestisce la cancellazione di un sottoprogetto.	
	 * @author edoardo
	 *
	 */
	public class DeleteSubProjectAsyncCallBack implements
			AsyncCallback<Boolean> {
		private final SubProject selected;
		private final List<SubProject> subprojects;

		public DeleteSubProjectAsyncCallBack(SubProject selected,
				List<SubProject> subprojects) {
			this.selected = selected;
			this.subprojects = subprojects;
		}

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			Window.alert(caught.getMessage());
		}

		@Override
		public void onSuccess(Boolean result) {
			final AutoProgressBar progressBar = new AutoProgressBar();
			
			progressBar.auto();
			progressBar.show();
			// TODO Auto-generated method stub
			if (result) {
				// ha trovato sotto progetti. L'operazione
				// di cancellazione non puo' andare avanti
				AlertMessageBox amb = new AlertMessageBox(
						"",
						"Operazione non possibile. Esistono timesheets associati");
				amb.setIcon(AlertMessageBox.ICONS.error());
				amb.show();
				return;
			}
			// verifico la presenza di utenti associati ai
			// sotto progetti
			UserServiceAsync userService = GWT
					.create(UserService.class);
			userService.hasSubProjects(subprojects,
					new AsyncCallback<Boolean>() {

						@Override
						public void onFailure(
								Throwable caught) {
							progressBar.hide();
						}

						@Override
						public void onSuccess(Boolean result) {
							if (result) {
								progressBar.hide();
								final ConfirmMessageBox mb = new ConfirmMessageBox(
										"Attenzione!!",
										"Sei sicuro di voler procedere alla cancellazione?");
								mb.addDialogHideHandler(new DialogHideHandler() {
									@Override
									public void onDialogHide(
											DialogHideEvent event) {
										switch (event
												.getHideButton()) {
										case YES:
											progressBar.show();
											ProjectServiceAsync service = GWT
													.create(ProjectService.class);
											service.deleteSubProject(
													selected.getId(),
													new AsyncCallback<Boolean>() {

														@Override
														public void onFailure(
																Throwable caught) {
															// TODO
															// Auto-generated
															// method
															// stub
															progressBar.hide();
														}

														@Override
														public void onSuccess(
																Boolean result) {
															if (result) {
																progressBar.hide();
																subProjectGrid.loadByRowSelected(parent
																		.getSelectionModel()
																		.getSelectedItem());
															}
														}

													});
											break;
										case NO:
											// perform NO
											// action
											break;
										default:
											// error, button
											// added with no
											// specific
											// action ready
										}
									}
								});
								mb.setWidth(300);
								mb.show();
								return;
							}
							ProjectServiceAsync service = GWT
									.create(ProjectService.class);
							service.deleteSubProject(
									selected.getId(),
									new AsyncCallback<Boolean>() {

										@Override
										public void onFailure(
												Throwable caught) {
											// TODO
											// Auto-generated
											// method
											// stub

										}

										@Override
										public void onSuccess(
												Boolean result) {
											if (result) {
												subProjectGrid.loadByRowSelected(parent
														.getSelectionModel()
														.getSelectedItem());
											}
										}

									});
						}
					});

		}
	}

	private final Grid<SubProject> child;
	private final Grid<Project> parent;
	private SubProjectsGrid subProjectGrid;
	private ProjectGrid projectGrid;

	public RemoveSubprojectHandler(SubProjectsGrid spGrid,ProjectGrid pGrid) {
		this.child = spGrid.getGrid();
		this.parent = pGrid.getGrid();
		this.subProjectGrid=spGrid;
		this.projectGrid=pGrid;
	}

	@Override
	public void onSelect(SelectEvent event) {
		// TODO Auto-generated method stub
		if (child.getSelectionModel().getSelectedItem() == null) {
			AlertMessageBox b = new AlertMessageBox("Error",
					"Selezionare la riga da eliminare");
			b.setIcon(AlertMessageBox.ICONS.warning());
			b.setModal(true);
			b.show();
			return;
		}

		final SubProject selected = subProjectGrid.getGrid()
				.getSelectionModel().getSelectedItem();

		// occorre prima verificare se ci sono timesheets associati a
		// questo progetto. Se ve ne sono parte il messaggio
		// "Operazione non possibile, esistono timesheets associati"
		// In seguito va verificato se ci sono utenti associati a questo
		// progetto!
		// In quest'ultimo caso va chiesta prima conferma all'utente
		TimesheetServiceAsync timesheetService = GWT
				.create(TimesheetService.class);
		final List<SubProject> subprojects = new ArrayList<SubProject>();
		subprojects.add(selected);
		timesheetService.hasSubproject(subprojects,
				new DeleteSubProjectAsyncCallBack(selected, subprojects));

	}
}
